package com.example.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.example.easyexcel.entity.User;
import com.example.easyexcel.service.EasyExcelService;
import com.example.easyexcel.utils.EasyExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/6/5
 */


@RestController
@RequestMapping
public class EasyExcelController {

    @Autowired
    private EasyExcelService EasyExcelService;


    @PostMapping("import")
    public void importExcel(@RequestPart("file") MultipartFile file) throws IOException {
        List<User> userList = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(User.class).sheet().doReadSync();
        for (User user : userList) {
            System.out.println(user);
        }
    }


    @GetMapping("/export")
    private void exportExcel(HttpServletResponse httpServletResponse) throws IOException {
        //从数据库中查询出需要进行导出的用户信息
        List<User> userList = new ArrayList<>();

        User User1 = new User();
        User1.setUserName("张三");
        User1.setAge(22);
        User1.setBirthday(EasyExcelUtil.formatDate("2000-10-11"));
        userList.add(User1);

        User User2 = new User();
        User2.setUserName("李四");
        User2.setAge(23);
        User2.setBirthday(EasyExcelUtil.formatDate("1999-5-3"));
        userList.add(User2);

        EasyExcelService.exportExcel(httpServletResponse, userList, User.class,"人员信息");
    }

    @GetMapping("/exportTemplate")
    private void exportExcelTemplate(HttpServletResponse httpServletResponse) throws IOException {
        /* 本质就是导出空数据 */
        EasyExcelService.exportExcelTemplate(httpServletResponse, User.class, "人员信息");
    }

}
